package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.dao.TaskDao;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskReportInfoVO;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.vo.*;
import com.sun.xml.bind.v2.model.core.EnumLeafInfo;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.text.Utilities;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {

    @Autowired
    private TaskStatusTypeService statusTypeService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskDetailsService taskDetailsService;


    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }


    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId, VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }


    @Transactional
    @Override
    public boolean createTask(TaskViewModel taskViewModel) throws LogicException {
        //跨服务查询售货机微服务，得到售货机的地址和区域id
        VmVO vm = vmService.getVMInfo(taskViewModel.getInnerCode());
        if (vm == null) {
            throw new LogicException("该机器不存在");
        }

        // 如果是投放工单
        if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_DEPLOY) {
            //TODO 判断这台设备是否有未完成的同类型工单，如果存在则不能创建
            //构建查询条件，根据ProductTypeId查询是否有同类型的工单
            LambdaQueryWrapper<TaskEntity> taskEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            taskEntityLambdaQueryWrapper.eq(TaskEntity::getProductTypeId, taskViewModel.getProductType());
            taskEntityLambdaQueryWrapper.eq(TaskEntity::getInnerCode, taskViewModel.getInnerCode());
            //查询数据库中的数据
            TaskEntity taskEntity = getOne(taskEntityLambdaQueryWrapper);
            //判断数据是否为空，如果不为空则抛出异常
            if (taskEntity != null) {
                throw new LogicException("存在同类型工单，不可添加投放工单");
            }
            //判断售货机状态是否为运营，如果是运营则抛出异常
            if (vm.getStatus() == VMSystem.VM_STATUS_RUNNING) {
                throw new LogicException("该机器为运营状态，不可投放");
            }
        }

        // 如果是补货工单
        if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_SUPPLY) {
            //TODO 判断这台设备是否有未完成的同类型工单，如果存在则不能创建
            //构建查询条件，根据ProductTypeId查询是否有同类型的工单
            LambdaQueryWrapper<TaskEntity> taskEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            taskEntityLambdaQueryWrapper.eq(TaskEntity::getProductTypeId, taskViewModel.getProductType());
            taskEntityLambdaQueryWrapper.eq(TaskEntity::getInnerCode, taskViewModel.getInnerCode());

            //判断售货机状态是否为运营，如果不是运营则抛出异常
            if (vm.getStatus() != VMSystem.VM_STATUS_RUNNING) {
                throw new LogicException("该机器未处于运营状态");
            }
        }

        // 如果是撤机工单
        if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_REVOKE) {
            //TODO 判断这台设备是否有未完成的同类型工单，如果存在则不能创建
            //构建查询条件，根据ProductTypeId查询是否有同类型的工单
            LambdaQueryWrapper<TaskEntity> taskEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            taskEntityLambdaQueryWrapper.eq(TaskEntity::getProductTypeId, taskViewModel.getProductType());
            taskEntityLambdaQueryWrapper.eq(TaskEntity::getInnerCode, taskViewModel.getInnerCode());

            //判断售货机状态是否为运营，如果不是运营则抛出异常
            if (vm.getStatus() != VMSystem.VM_STATUS_RUNNING) {
                throw new LogicException("该机器未处于运营状态");
            }
        }

        //跨服务查询用户微服务，得到用户名
        UserVO user = userService.getUser(taskViewModel.getUserId());
        if (user == null) {
            throw new LogicException("该用户不存在");
        }

        //新增工单表记录
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setTaskCode(generateTaskCode());//工单编号
        BeanUtils.copyProperties(taskViewModel, taskEntity);//复制属性
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);//工单状态
        taskEntity.setProductTypeId(taskViewModel.getProductType());//工单类型

        taskEntity.setAddr(vm.getNodeAddr());//地址
        taskEntity.setRegionId(vm.getRegionId());//区域
        taskEntity.setUserName(user.getUserName());//用户名
        this.save(taskEntity);
        //如果是补货工单，向 工单明细表插入记录
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) {
            taskViewModel.getDetails().forEach(d -> {
                TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties(d, detailsEntity);
                detailsEntity.setTaskId(taskEntity.getTaskId());
                taskDetailsService.save(detailsEntity);
            });
        }

        return true;
    }


    /**
     * 生成工单编号
     *
     * @return
     */
    private String generateTaskCode() {
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key = "lkd.task.code." + date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            redisTemplate.opsForValue().set(key, 1L, Duration.ofDays(1));
            return date + "0001";
        }
        return date + Strings.padStart(redisTemplate.opsForValue().increment(key, 1).toString(), 4, '0');
    }


    @Override
    public boolean accept(Long id) {
        TaskEntity task = this.getById(id);  //查询工单
        // 需要判断当前工单是否是待处理状态，如果不是则抛出异常。
        if (task.getTaskStatus() != VMSystem.TASK_STATUS_CREATE) {
            throw new LogicException("该工单不处于待处理状态");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);//修改工单状态为进行
        return this.updateById(task);
    }

    @Override
    public boolean cancelTask(Long id, CancelTaskViewModel cancelVM) {
        TaskEntity task = this.getById(id);  //查询工单
        task.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        task.setDesc(cancelVM.getDesc());
        return this.updateById(task);
    }

    @Override
    public boolean completeTask(long id) {
        TaskEntity taskEntity = this.getById(id);
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);//修改工单状态
        this.updateById(taskEntity);
        return true;
    }

    /**
     * @param start  开始查询时间
     * @param end    结束查询时间
     * @param repair 是否是运维工单
     * @param Status 工单状态（查询创建(待处理)TASK_STATUS_CREATE、进行TASK_STATUS_PROGRESS、取消TASK_STATUS_CANCEL、完成TASK_STATUS_FINISH）
     * @return
     */
    public Integer Statistics(LocalDateTime start, LocalDateTime end, Boolean repair, Integer Status) {
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
//        根据时间范围查询
        qw.ge(TaskEntity::getUpdateTime, start).le(TaskEntity::getUpdateTime, end);
//        如果是运维工单，需要排除掉运营工单(补货工单）
        if (repair) {
            qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
        } else {
//            如果是运营工单，只需要根据补货工单id进行查询即可
            qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
        }

        if (Status != null) {
            qw.eq(TaskEntity::getTaskStatus, Status);
        }
        return this.count(qw);
    }

    @Override
    public List<TaskReportInfoVO> taskReportInfo(LocalDateTime start, LocalDateTime end) {
        //返回结果集
        List<TaskReportInfoVO> res = new ArrayList<>();
        //时间获取
        Date date = new Date();
        //SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = dateFormat.format(date);

        //运维通用方法    Statistics(start,end,true,VMSystem.)

        //运维工单
        TaskReportInfoVO taskReportInfoVO = new TaskReportInfoVO();

        //工单总数
        taskReportInfoVO.setTotal(Statistics(start, end, true, null));
        //完成总数
        taskReportInfoVO.setCompletedTotal(Statistics(start, end, true, VMSystem.TASK_STATUS_FINISH));
        //是否是运维工单统计
        taskReportInfoVO.setRepair(true);
        //工作人数
        taskReportInfoVO.setWorkerCount(userService.getRepairerCount());
        //进行中总数
        taskReportInfoVO.setProgressTotal(Statistics(start, end, true, VMSystem.TASK_STATUS_PROGRESS));
        //拒绝总数
        taskReportInfoVO.setCancelTotal(Statistics(start, end, true, VMSystem.TASK_STATUS_CANCEL));
        //统计的日期
        taskReportInfoVO.setDate(format);

        //运维结果集封装
        res.add(taskReportInfoVO);

        //    运营通用方法    Statistics(start,end,false,VMSystem.)


        //运营工单
        TaskReportInfoVO taskOperateInfoVO = new TaskReportInfoVO();
        //工单总数
        taskOperateInfoVO.setTotal(Statistics(start, end, false, null));
        //完成总数
        taskOperateInfoVO.setCompletedTotal(Statistics(start, end, false, VMSystem.TASK_STATUS_FINISH));
        //是否是运维工单统计
        taskOperateInfoVO.setRepair(false);
        //工作人数
        taskOperateInfoVO.setWorkerCount(userService.getOperatorCount());
        //进行中总数
        taskOperateInfoVO.setProgressTotal(Statistics(start, end, false, VMSystem.TASK_STATUS_PROGRESS));
        //拒绝总数
        taskOperateInfoVO.setCancelTotal(Statistics(start, end, false, VMSystem.TASK_STATUS_CANCEL));
        //统计的日期
        taskOperateInfoVO.setDate(format);
        //运营结果集封装
        res.add(taskOperateInfoVO);

        return res;
    }

    /**
     *
     * @param start
     * @param end
     * @param isRepair 运维人员是true 运营人员是false
     * @param regionId 区域id
     * @return
     */
    @Override
    public List<UserWorkVO> userWorkTop10(LocalDate start, LocalDate end, Boolean isRepair, Integer regionId) {
        var taskEntityLambdaQueryWrapper = new QueryWrapper<TaskEntity>();
        taskEntityLambdaQueryWrapper
                .select("count(user_id) as user_id,user_name")
                .lambda()
                .ge(TaskEntity::getUpdateTime,start)
                .lt(TaskEntity::getUpdateTime,end.plusDays(1))
                .eq(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_FINISH)
                .groupBy(TaskEntity::getUserName)
                .orderByDesc(TaskEntity::getUserId)
                .last("limit 10");

        if(regionId >0){
            taskEntityLambdaQueryWrapper.lambda().eq(TaskEntity::getRegionId,regionId);
        }
        if(isRepair){
            taskEntityLambdaQueryWrapper.lambda().ne(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }else {
            taskEntityLambdaQueryWrapper.lambda().eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }

        List<UserWorkVO> collect = this.list(taskEntityLambdaQueryWrapper).stream().map(t -> {
            var userWork = new UserWorkVO();
            userWork.setUserName(t.getUserName());
            userWork.setWorkCount(t.getUserId());
            return userWork;
        }).collect(Collectors.toList());
        return collect;
//        只统计已完成的工单
//        taskEntityLambdaQueryWrapper.eq(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_FINISH);
//        根据时间范围查询
//        taskEntityLambdaQueryWrapper.ge(TaskEntity::getUpdateTime, start).le(TaskEntity::getUpdateTime, end);

//        if (isRepair){
//            taskEntityLambdaQueryWrapper.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
//        }else {
//            taskEntityLambdaQueryWrapper.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
//        }
//        if (regionId != 0){
//            taskEntityLambdaQueryWrapper.eq(TaskEntity::getRegionId, regionId);
//        }
//        taskEntityLambdaQueryWrapper.groupBy(TaskEntity::getUserName);
//
//
//        Map<String, Object> map = getMap(taskEntityLambdaQueryWrapper);
//        int count = count(taskEntityLambdaQueryWrapper);
//        list.add(userWorkVO);
    }


    @Override
    public List<TaskCollectVO> collectReport(LocalDate start, LocalDate end) {
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
//        根据时间范围查询
        qw.ge(TaskEntity::getUpdateTime, start).le(TaskEntity::getUpdateTime, end);

        TaskCollectVO taskCollectVO = new TaskCollectVO();
        //时间获取
        Date date = new Date();
        //SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = dateFormat.format(date);
        taskCollectVO.setCollectDate(LocalDate.parse(format));
        taskCollectVO.setCancelCount(13);
        taskCollectVO.setFinishCount(14);
        taskCollectVO.setProgressCount(15);
        List<TaskCollectVO> taskCollectVOList = new ArrayList<>();
        taskCollectVOList.add(taskCollectVO);
        //TODO 工单状态统计（柱状图）
        return taskCollectVOList;
    }
}
